{extend name='table'}

{block name="button"}
    <button class="layui-btn layui-btn-sm" data-table-id="RecordTable" data-action='{:url("finish")}' data-rule="id#{id}">
        <i class="layui-icon layui-icon-ok"></i> 结束并结算
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-danger" data-table-id="RecordTable" data-action='{:url("remove")}' data-rule="id#{id}">
        <i class="layui-icon layui-icon-delete"></i> 删除
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-normal" data-table-id="RecordTable" data-action='{:url("state")}' data-rule="id#{id};status#1" data-confirm="确定批量标记为正常吗？">
        <i class="layui-icon layui-icon-ok-circle"></i> 标记正常
    </button>
    <button class="layui-btn layui-btn-sm layui-btn-warm" data-table-id="RecordTable" data-action='{:url("state")}' data-rule="id#{id};status#2" data-confirm="确定批量标记为无效吗？">
        <i class="layui-icon layui-icon-close-fill"></i> 标记无效
    </button>
    <button class="layui-btn layui-btn-sm" style="background-color: #FF5722; color: white;" onclick="openBatchRecalculateDialog()">
        <i class="layui-icon layui-icon-refresh"></i> 一键重新计算积分
    </button>
    <div style="display:inline-block; margin-left:10px; color:#999; font-size:12px;">
        💡 提示：标记正常/无效用于手动修正记录状态，不会重新计算积分
    </div>
{/block}

{block name="search"}
    <form class="layui-form layui-form-pane form-search" id="RecordSearchForm" data-table-id="RecordTable" onsubmit="return false">
        <div class="layui-form-item layui-inline">
            <label class="layui-form-label">会员姓名</label>
            <div class="layui-input-inline">
                <input name="member_name" value="{$get.member_name|default=''}" placeholder="请输入会员姓名" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-inline">
            <label class="layui-form-label">卡号</label>
            <div class="layui-input-inline">
                <input name="card_no" value="{$get.card_no|default=''}" placeholder="磁卡号" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-inline">
            <label class="layui-form-label">状态</label>
            <div class="layui-input-inline">
                <select name="status">
                    <option value="">- 全部 -</option>
                    <option value="1" {if input('get.status') == '1'}selected{/if}>正常</option>
                    <option value="2" {if input('get.status') == '2'}selected{/if}>无效</option>
                    <option value="3" {if input('get.status') == '3'}selected{/if}>进行中</option>
                </select>
            </div>
        </div>
        {if $isMaster}
        <div class="layui-form-item layui-inline">
            <label class="layui-form-label">门店</label>
            <div class="layui-input-inline">
                <select name="store_id">
                    <option value="">- 全部 -</option>
                    {foreach $stores as $s}
                    <option value="{$s.id}" {if input('get.store_id') == $s.id}selected{/if}>{$s.name}</option>
                    {/foreach}
                </select>
            </div>
        </div>
        {/if}
        <div class="layui-form-item layui-inline">
            <label class="layui-form-label">开始时间</label>
            <div class="layui-input-inline">
                <input data-date-range name="start_time" value="{$get.start_time|default=''}" placeholder="- 选择时间范围 -" class="layui-input">
            </div>
        </div>
        <div class="layui-form-item layui-inline">
            <button class="layui-btn" type="submit"><i class="layui-icon layui-icon-search"></i> 搜 索</button>
            <button class="layui-btn layui-btn-primary" type="reset"><i class="layui-icon layui-icon-refresh-1"></i> 重 置</button>
        </div>
    </form>
{/block}

{block name="content"}
    <table id="RecordTable" data-url="{:sysuri('index')}" data-target-search="form.form-search"></table>
{/block}

{block name="script"}
<script>
layui.use(['jquery', 'layer'], function () {
  var $ = layui.$;
  var layer = layui.layer;

  let cols = [
    {type:'checkbox'},
    {field:'id', title:'ID', width:70, sort:true},
    {field:'member_name', title:'会员姓名', width:120},
    {field:'member_phone', title:'手机号', width:120},
    {field:'card_no', title:'磁卡号', width:140},
    {field:'store_name', title:'门店', width:140},
    {field:'start_time', title:'开始时间', width:170, sort:true},
    {field:'end_time', title:'结束时间', width:170, sort:true},
    {field:'duration_minutes', title:'时长(分钟)', width:110, sort:true},
    {field:'points', title:'积分', width:80, sort:true},
    {field:'status', title:'状态', width:90, templet: d=> d.status==1?'<span class="color-green">正常</span>':(d.status==2?'<span class="color-red">无效</span>':'<span class="color-blue">进行中</span>')},
    {field:'create_time', title:'创建时间', width:170, sort:true},
    {toolbar:'#ToolbarTpl', title:'操作', minWidth:180, fixed:'right'}
  ];
  $('#RecordTable').layTable({ even:true, height:'full-200', cols: [cols] });

  // 重新计算积分函数
  window.recalculatePoints = function(recordId, memberName, currentPoints) {
    var loadIndex = layer.load(2, {shade: 0.3});

    $.ajax({
      url: '{:url("recalculate")}',
      type: 'POST',
      data: { id: recordId },
      dataType: 'json',
      success: function(res) {
        layer.close(loadIndex);

        if (res.code === 1) {
          var data = res.data;
          var oldPoints = data.old_points;
          var newPoints = data.new_points;
          var diff = data.diff;
          var details = data.details || [];
          var unitMinutes = data.unit_minutes || 10;
          var diffText = diff > 0 ? '+' + diff : diff;
          var diffColor = diff > 0 ? 'green' : (diff < 0 ? 'red' : 'gray');

          if (diff === 0) {
            layer.msg('积分无变化，无需更新', {icon: 0});
            return;
          }

          // 构建计算过程表格
          var detailsHtml = '';
          if (details.length > 0) {
            detailsHtml = '<div style="margin-top: 15px;">' +
              '<div style="font-size: 13px; font-weight: bold; margin-bottom: 8px; color: #333;">📊 计算过程：</div>' +
              '<div style="font-size: 12px; color: #666; margin-bottom: 8px;">' +
              '⏰ 开始时间：' + data.start_time + ' &nbsp;&nbsp; 结束时间：' + data.end_time + ' &nbsp;&nbsp; 时长：' + data.duration_minutes + ' 分钟' +
              '</div>' +
              '<table class="layui-table" lay-skin="line" style="margin: 0;">' +
              '<thead><tr>' +
              '<th style="text-align: center;">时间段</th>' +
              '<th style="text-align: center;">分钟数</th>' +
              '<th style="text-align: center;">单位数</th>' +
              '<th style="text-align: center;">单位积分</th>' +
              '<th style="text-align: center;">小计</th>' +
              '</tr></thead>' +
              '<tbody>';

            for (var i = 0; i < details.length; i++) {
              var item = details[i];
              detailsHtml += '<tr>' +
                '<td style="text-align: center;">' + item.segment + '</td>' +
                '<td style="text-align: center;">' + item.minutes + ' 分钟</td>' +
                '<td style="text-align: center;">' + item.units + ' 个</td>' +
                '<td style="text-align: center;">' + item.points_per_unit + ' 分/单位</td>' +
                '<td style="text-align: center; font-weight: bold; color: #5FB878;">' + item.points + ' 分</td>' +
                '</tr>';
            }

            detailsHtml += '</tbody></table>' +
              '<div style="font-size: 12px; color: #999; margin-top: 5px;">💡 单位时长：' + unitMinutes + ' 分钟</div>' +
              '</div>';
          }

          var content = '<div style="padding: 20px; line-height: 2;">' +
            '<div style="font-size: 14px; margin-bottom: 15px;">会员：<strong>' + memberName + '</strong></div>' +
            '<div style="font-size: 14px;">原积分：<strong>' + oldPoints + '</strong> 分</div>' +
            '<div style="font-size: 14px;">重新计算：<strong>' + newPoints + '</strong> 分</div>' +
            '<div style="font-size: 16px; margin-top: 10px;">差值：<strong style="color: ' + diffColor + ';">' + diffText + '</strong> 分 ' +
            (diff > 0 ? '（需要增加）' : '（需要扣减）') + '</div>' +
            detailsHtml +
            '<div style="margin-top: 15px; padding: 10px; background: #f8f8f8; border-radius: 4px; font-size: 12px; color: #666;">' +
            '💡 提示：点击"确认更新"后将更新签到记录积分，并调整会员总积分' +
            '</div>' +
            '</div>';

          layer.confirm(content, {
            title: '积分重新计算',
            btn: ['确认更新', '取消'],
            area: ['600px', 'auto'],
            yes: function(index) {
              layer.close(index);
              confirmUpdatePoints(recordId, oldPoints, newPoints, diff);
            }
          });
        } else {
          layer.msg(res.msg || '计算失败', {icon: 2});
        }
      },
      error: function() {
        layer.close(loadIndex);
        layer.msg('网络错误，请重试', {icon: 2});
      }
    });
  };

  // 确认更新积分
  function confirmUpdatePoints(recordId, oldPoints, newPoints, diff) {
    var loadIndex = layer.load(2, {shade: 0.3});

    $.ajax({
      url: '{:url("updatePoints")}',
      type: 'POST',
      data: {
        id: recordId,
        old_points: oldPoints,
        new_points: newPoints,
        diff: diff
      },
      dataType: 'json',
      success: function(res) {
        layer.close(loadIndex);

        if (res.code === 1) {
          layer.msg(res.msg || '更新成功', {icon: 1});
          // 刷新表格
          $('#RecordTable').trigger('reload');
        } else {
          layer.msg(res.msg || '更新失败', {icon: 2});
        }
      },
      error: function() {
        layer.close(loadIndex);
        layer.msg('网络错误，请重试', {icon: 2});
      }
    });
  }

  // 打开批量重新计算对话框
  window.openBatchRecalculateDialog = function() {
    var content = '<div style="padding: 20px;">' +
      '<form class="layui-form" id="batchRecalculateForm">' +
      '<div class="layui-form-item">' +
      '<label class="layui-form-label">开始时间</label>' +
      '<div class="layui-input-block">' +
      '<input type="text" name="start_time" id="batchStartTime" placeholder="请选择开始时间" class="layui-input" required>' +
      '</div>' +
      '</div>' +
      '<div class="layui-form-item">' +
      '<label class="layui-form-label">结束时间</label>' +
      '<div class="layui-input-block">' +
      '<input type="text" name="end_time" id="batchEndTime" placeholder="请选择结束时间" class="layui-input" required>' +
      '</div>' +
      '</div>' +
      '<div style="padding: 10px; background: #fff3cd; border-radius: 4px; font-size: 12px; color: #856404; margin-top: 15px;">' +
      '⚠️ 警告：<br>' +
      '1. 将重新计算指定时间范围内所有"正常"状态的签到记录<br>' +
      '2. 点击"开始计算"后将<strong>立即更新数据库</strong>，此操作不可撤销<br>' +
      '3. 只会更新积分有变化的记录<br>' +
      '4. 建议先小范围测试，确认无误后再大范围操作' +
      '</div>' +
      '</form>' +
      '</div>';

    layer.open({
      type: 1,
      title: '一键重新计算积分',
      area: ['500px', 'auto'],
      content: content,
      btn: ['开始计算', '取消'],
      yes: function(index) {
        var startTime = $('#batchStartTime').val();
        var endTime = $('#batchEndTime').val();

        if (!startTime || !endTime) {
          layer.msg('请选择开始时间和结束时间', {icon: 0});
          return;
        }

        // 二次确认
        layer.confirm('确定要批量重新计算并更新积分吗？此操作不可撤销！', {
          title: '确认操作',
          btn: ['确定', '取消']
        }, function(confirmIndex) {
          layer.close(index);
          layer.close(confirmIndex);
          batchRecalculatePoints(startTime, endTime);
        });
      },
      success: function() {
        // 初始化日期时间选择器
        layui.use(['laydate'], function() {
          var laydate = layui.laydate;

          laydate.render({
            elem: '#batchStartTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss'
          });

          laydate.render({
            elem: '#batchEndTime',
            type: 'datetime',
            format: 'yyyy-MM-dd HH:mm:ss'
          });
        });
      }
    });
  };

  // 批量重新计算并更新积分
  function batchRecalculatePoints(startTime, endTime) {
    var loadIndex = layer.load(2, {shade: 0.3, content: '正在计算并更新中，请稍候...'});

    $.ajax({
      url: '{:url("batchRecalculate")}',
      type: 'POST',
      data: {
        start_time: startTime,
        end_time: endTime
      },
      dataType: 'json',
      success: function(res) {
        layer.close(loadIndex);

        if (res.code === 1) {
          var data = res.data;
          var totalCount = data.total_count || 0;
          var successCount = data.success_count || 0;
          var noChangeCount = data.no_change_count || 0;
          var errorCount = data.error_count || 0;
          var totalDiff = data.total_diff || 0;

          var diffColor = totalDiff > 0 ? 'green' : (totalDiff < 0 ? 'red' : 'gray');
          var diffText = totalDiff > 0 ? '+' + totalDiff : totalDiff;

          var content = '<div style="padding: 20px; font-size: 14px; line-height: 2;">' +
            '<div style="text-align: center; margin-bottom: 20px;">' +
            '<i class="layui-icon layui-icon-ok-circle" style="font-size: 50px; color: #5FB878;"></i>' +
            '<div style="font-size: 18px; font-weight: bold; margin-top: 10px;">批量更新完成</div>' +
            '</div>' +
            '<div style="background: #f8f8f8; padding: 15px; border-radius: 4px;">' +
            '<div>📊 扫描记录：<strong>' + totalCount + '</strong> 条</div>' +
            '<div>✅ 成功更新：<strong style="color: #5FB878;">' + successCount + '</strong> 条</div>';

          if (noChangeCount > 0) {
            content += '<div>➖ 无需更新：<strong>' + noChangeCount + '</strong> 条</div>';
          }

          if (errorCount > 0) {
            content += '<div>❌ 更新失败：<strong style="color: #FF5722;">' + errorCount + '</strong> 条</div>';
          }

          content += '<div>💰 总积分变化：<strong style="color: ' + diffColor + ';">' + diffText + '</strong> 分</div>' +
            '</div>' +
            '</div>';

          layer.open({
            type: 1,
            title: '更新结果',
            area: ['500px', 'auto'],
            content: content,
            btn: ['确定'],
            yes: function(index) {
              layer.close(index);
              // 刷新表格
              $('#RecordTable').trigger('reload');
            }
          });
        } else {
          // 友好的提示信息
          layer.msg(res.info || res.msg || '操作失败', {icon: 0, time: 2000});
        }
      },
      error: function() {
        layer.close(loadIndex);
        layer.msg('网络错误，请重试', {icon: 2});
      }
    });
  }
});
</script>

<script type="text/html" id="ToolbarTpl">
    <a class="layui-btn layui-btn-xs" data-title="查看会员" data-open='{:url("checkin/member/index")}?keyword={{d.member_phone}}'>会 员</a>
    {{# if(d.status==3){ }}
    <a class="layui-btn layui-btn-xs" data-table-id="RecordTable" data-action='{:url("finish")}' data-value="id={{d.id}}">结束并结算</a>
    {{# } }}
    {{# if(d.status==1){ }}
    <a class="layui-btn layui-btn-xs layui-btn-primary" onclick="recalculatePoints({{d.id}}, '{{d.member_name}}', {{d.points}})">重新计算积分</a>
    {{# } }}
    <a class="layui-btn layui-btn-normal layui-btn-xs" data-table-id="RecordTable" data-action='{:url("state")}' data-confirm="确定标记为正常吗？" data-value="id#{{d.id}};status#1">标记正常</a>
    <a class="layui-btn layui-btn-warm layui-btn-xs" data-table-id="RecordTable" data-action='{:url("state")}' data-confirm="确定标记为无效吗？" data-value="id#{{d.id}};status#2">标记无效</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" data-confirm="确定删除该记录吗？" data-action='{:url("remove")}' data-value="id#{{d.id}}">删 除</a>
</script>
{/block}
